import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_appgetwe/provider/LoginProvider.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:provider/provider.dart';
import 'package:waterfall_flow/waterfall_flow.dart';

class HomeIndexPro extends StatefulWidget {
  @override
  _HomeIndexProState createState() => _HomeIndexProState();
}

class _HomeIndexProState extends State<HomeIndexPro> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(
      //   title: Text("layout"),
      //   centerTitle: true,
      // ),
      body: HomeIndex(),
    );
  }
}

class HomeIndex extends StatefulWidget {
  @override
  _HomeIndexState createState() => _HomeIndexState();
}

class _HomeIndexState extends State<HomeIndex> {
  List<Map> str = [];
  List<Color> colors = <Color>[];
  int count = 2;
  Color getRandomColor(int index) {
    if (index >= colors.length) {
      colors.add(Color.fromARGB(255, Random.secure().nextInt(255),
          Random.secure().nextInt(255), Random.secure().nextInt(255)));
    }
    return colors[index];
  }

  late ScrollController _controller = ScrollController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    for (int i = 1; i < 30; i++) {
      str.add(
        {
          "headerImage": "lib/assets/headerimage.jpg",
          "image": "lib/assets/bg_login.jpg",
          "id": i,
          "desc": "标题标题标题..........................",
        },
      );
    }
    print(str[1]['image']);
    print(str[1]['desc']);
    print("打印获取到的状态");
    // print(context.read<LoginProvider>().getUserName());
    // print(context.read<LoginProvider>().getIsLogin());

    _controller.addListener(() {
      print(_controller.offset);
    });

    // if(_controller.position.pixels == _controller.position.maxScrollExtent){
    //   print("到底了......");
    // }

    //print(_controller.position.pixels);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  void _getList() {
    print("执行方法了..");
    for (int i = 1; i < 50; i++) {
      str.add(
        {
          "headerImage": "lib/assets/headerimage.jpg",
          "image": "lib/assets/bg_login.jpg",
          "id": i,
          "desc": "标题标题标题..........................",
        },
      );
    }
    //EasyLoading.dismiss();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawerEnableOpenDragGesture: true,
      resizeToAvoidBottomInset: true,
      endDrawerEnableOpenDragGesture: true,
      //resizeToAvoidBottomPadding:true,
      // appBar: AppBar(
      //   title: Text("layout"),
      //   centerTitle: true,
      // ),
      body: CustomScrollView(
        controller: _controller,
        slivers: [
          SliverToBoxAdapter(
            child: Container(
              height: 30,
              child: Text(
                "Extra space for you",
                style: TextStyle(color: Colors.white, fontSize: 25),
              ),
              //color: Colors.green,
              alignment: Alignment.center,
            ),
          ),
          // Positioned(
          //     top: 1,
          //     child: Container(
          //       height: 20,
          //       color: Colors.blue,
          //     )),
          SliverWaterfallFlow(
              delegate: SliverChildBuilderDelegate((BuildContext c, int index) {
                if (index < str.length) {
                  return Padding(
                    padding:
                        EdgeInsets.only(left: 2, bottom: 2, right: 2, top: 2),
                    child: GestureDetector(
                      onTap: () {
                        print(1);
                        print(str[index]['id'].toString());
                      },
                      child: str[index]['id'] != ""
                          ? Container(
                              child: Stack(
                                children: [
                                  Positioned(
                                    bottom: 10,
                                    left: 10,
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Container(
                                          margin: EdgeInsets.only(right: 5),
                                          height: 28,
                                          width: 28,
                                          decoration: BoxDecoration(
                                              borderRadius:
                                                  BorderRadius.circular(40),
                                              image: new DecorationImage(
                                                  image: AssetImage(str[index]
                                                          ['headerImage'] +
                                                      ""),
                                                  fit: BoxFit.cover)),
                                        ),
                                        Text(
                                          "" + str[1]['desc'],
                                          style: TextStyle(
                                              fontSize: 16,
                                              fontWeight: FontWeight.w600,
                                              color: Colors.yellow,
                                              overflow: TextOverflow.ellipsis),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                              decoration: BoxDecoration(
                                //border: Border.all(color: Colors.cyanAccent),
                                boxShadow: [
                                  BoxShadow(
                                      offset: Offset(0.1, 0.1),
                                      //color: Colors.green,
                                      blurRadius: 1)
                                ],
                                borderRadius: BorderRadius.circular(5),
                                color: getRandomColor(index),
                                image: new DecorationImage(
                                    image: AssetImage(str[index]['image'] + ""),
                                    fit: BoxFit.cover),
                              ),
                              height: (Random.secure().nextInt(50)) + 220,
                            )
                          : null,
                    ),
                  );
                } else {
                  //EasyLoading.show(status: 'loading...');
                  print("到底了.....");
                  _getList();

                  return null;
                }
              }),
              gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
                closeToTrailing: true,
                lastChildLayoutTypeBuilder: (index) => index == str.length
                    ? LastChildLayoutType.foot
                    : LastChildLayoutType.none,
                crossAxisCount: count,
                mainAxisSpacing: 1.0,
                crossAxisSpacing: 1.0,
              )),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.track_changes),
        onPressed: () {
          setState(() {
            count++;
          });
        },
      ),
    );
  }
}
